package com.magina.antiPro.controller;

import com.magina.antiPro.model.Members;
import com.magina.antiPro.model.WeiXinUser;
import com.magina.antiPro.response.Response;
import com.magina.antiPro.service.WechatService;
import com.magina.antiPro.util.Decript;
import com.magina.antiPro.util.WeiXinUtils;
import lombok.extern.slf4j.Slf4j;
import org.assertj.core.util.Lists;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "Wechat")
@Slf4j
public class WecharDataController {

    @Autowired
    private WechatService wechatService;

    @GetMapping(value = "/testData")
    public Object testWechar() {
        log.info("进入testData");
        List result = Lists.newArrayList();
        for (int i = 0; i < 5; i++) {
            result.add("我就是测试案例" + i + ",");
        }

        return result;
    }

    @GetMapping(value = "/getMemberInfo")
    public Response getMemberInfo(HttpServletRequest request) throws Exception {
        log.info("=============================进入Wechat==================================");
        String code = request.getParameter("code");
        Members members = wechatService.getMembersInfo(code);
        if (members.getEmail() == null || "".equals(members.getEmail())) {
            String str = ("您的邮箱为空或者没有配置相关权限，请联系管理员，谢谢。");
            Response responseEntity = Response.fail("333", str);
            return responseEntity;
        }
        return Response.succeed(members);
    }

    //token
    private final String token = "cass";

    @GetMapping(value = "/testInfo")
    public void testInfo(HttpServletRequest request, HttpServletResponse response) throws Exception {
        log.info("=============================进入Wechat==================================");
        log.info(request.toString());
        System.out.println("开始签名校验");
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        //排序
        String sortString = sort(token, timestamp, nonce);
        //加密
        String mytoken = Decript.SHA1(sortString);
        //校验签名
        if (mytoken != null && mytoken != "" && mytoken.equals(signature)) {
            System.out.println("签名校验通过。");
            response.getWriter().print(echostr); //如果检验成功输出echostr，微信服务器接收到此输出，才会确认检验完成。
        }
    }

    public static String sort(String token, String timestamp, String nonce) {
        String[] strArray = {token, timestamp, nonce};
        Arrays.sort(strArray);

        StringBuilder sbuilder = new StringBuilder();
        for (String str : strArray) {
            sbuilder.append(str);
        }
        return sbuilder.toString();
    }

    @RequestMapping("/tologin/userinfo")
    public String check(HttpServletRequest request, HttpSession session, Map<String, Object> map) {
        //首先判断一下session中，是否有保存着的当前用户的信息，有的话，就不需要进行重复请求信息
        WeiXinUser weiXinUser = null;
        if (session.getAttribute("currentUser") != null) {
            weiXinUser = (WeiXinUser) session.getAttribute("currentUser");
        } else {
            /**
             * 进行获取openId，必须的一个参数，这个是当进行了授权页面的时候，再重定向了我们自己的一个页面的时候，
             * 会在request页面中，新增这个字段信息，要结合这个ProjectConst.Get_WEIXINPAGE_Code这个常量思考
             */
            String code = request.getParameter("code");
            try {
                //得到当前用户的信息(具体信息就看weixinUser这个javabean)
                weiXinUser = getTheCode(session, code);
                //将获取到的用户信息，放入到session中
                session.setAttribute("currentUser", weiXinUser);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        map.put("weiXinUser", weiXinUser);
        return "hello";
    }

    @RequestMapping(value = "/tologin/userinfoByButton",method = RequestMethod.GET)
    public String userinfoByButton(HttpServletRequest request) {
        //首先判断一下session中，是否有保存着的当前用户的信息，有的话，就不需要进行重复请求信息
        Map data = xmlToMap(request);
        log.info(data.toString());
        return "hello";
    }

    /**
     * 获取用户的openId
     *
     * @param session
     * @param code
     * @return 返回封装的微信用户的对象
     */
    private WeiXinUser getTheCode(HttpSession session, String code) {
        Map<String, String> authInfo = new HashMap<>();
        String openId = "";
        if (code != null) {
            // 调用根据用户的code得到需要的授权信息
            authInfo = wechatService.getAuthInfo(code);
            //获取到openId
            openId = authInfo.get("Openid");
        }
        // 获取基础刷新的接口访问凭证（目前还没明白为什么用authInfo.get("AccessToken");这里面的access_token就不行）
        String accessToken = WeiXinUtils.getAccessToken().getAccess_token();
        //获取到微信用户的信息
        WeiXinUser userinfo = wechatService.getUserInfo(accessToken, openId);

        return userinfo;
    }

    /**
     * XML格式转为map格式
     *
     * @param request
     * @return
     */
    public static Map<String, String> xmlToMap(HttpServletRequest request) {
        Map<String, String> map = new HashMap<String, String>();
        try {
            InputStream inputStream = null;
            inputStream = request.getInputStream();
            SAXReader reader = new SAXReader();
            Document doc = reader.read(inputStream);
            Element rootElement = doc.getRootElement();
            List<Element> elements = rootElement.elements();
            for (Element el : elements) {
                map.put(el.getName(), el.getText());
            }
            inputStream.close();
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


}
